import { defineStore } from "pinia"
import Router from "../../router"
const historyList = JSON.parse(window.localStorage.getItem("history") || "[]")
function saveHistory(value) {
	window.localStorage.setItem("history", JSON.stringify(value))
}
export const useHistoryStore = defineStore("history", {
	state() {
		return {
			historyList,
		}
	},
	actions: {
		// 增加历史
		addHistory(item) {
			if (item.path == "/" || item.path == "") return
			const index = this.findIndex(item.path)
			if (index > -1) {
				this.historyList.splice(index, 1, item)
			} else {
				this.historyList.push(item)
			}
			saveHistory(this.historyList)
		},
		// 删除历史
		deleteHistory(path = Router.currentRoute.value.path) {
			const index = this.findIndex(path)
			if (index > -1) {
				this.historyList.splice(index, 1)
			}
			saveHistory(this.historyList)
		},
		// 上传历史
		uploadHistory(historyList = []) {
			this.historyList = historyList
			saveHistory(this.historyList)
		},
		// 发现历史
		findHistory(path) {
			return this.historyList.find(history => history.path === path)
		},
		// 发现index
		findIndex(path) {
			return this.historyList.findIndex(item => item.path === path)
		},
	},
})
